﻿using Tutorial1_Spawner;
using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Jobs;
using Unity.Mathematics;
using Unity.Profiling;
using Unity.Transforms;

namespace Tutorial5_PTR
{
    [BurstCompile]
    [UpdateInGroup(typeof(Tutorial5SystemGroup))]
    public partial struct TransPtrUpdateSystem : ISystem
    {
        private ProfilerMarker _marker;

        public void OnCreate(ref SystemState state)
        {
            _marker = new ProfilerMarker("JobSYSTEM");
        }

        public void OnUpdate(ref SystemState state)
        {
            //_marker.Begin();
            // 先找到现在已有的LocalTransform和CubeTag
            EntityQueryBuilder builder = new EntityQueryBuilder(Allocator.TempJob).WithAll<LocalTransform, CubeTag>();
            var query = state.GetEntityQuery(builder);
            var entities = query.ToEntityArray(Allocator.TempJob);
            // 创建并赋值到Array里
            NativeArray<TransformAoS> transformAos = new NativeArray<TransformAoS>(entities.Length, Allocator.TempJob);
            for (int i = 0; i < entities.Length; i++)
            {
                var localTransform = state.EntityManager.GetComponentData<LocalTransform>(entities[i]);
                var aoS = transformAos[i];
                aoS.position = localTransform.Position;
                aoS.rotation = localTransform.Rotation.value;
                aoS.scale = localTransform.Scale;
                transformAos[i] = aoS;
            }
            // 在JOB中更新
            TransformAOSJob job = new TransformAOSJob()
            {
                transform_AOS = transformAos,
                deltaTime = SystemAPI.Time.DeltaTime,
                velocity = new float3(1, 0, 0)
            };
         
            // 执行JOB
            job.ScheduleParallel(entities.Length, 16, new JobHandle()).Complete();
            
           //_marker.End(); 
            // 将修改的数据还原回去
            for (int i = 0; i < entities.Length; i++)
            {
                var localTransform = state.EntityManager.GetComponentData<LocalTransform>(entities[i]);
                localTransform.Position = transformAos[i].position;
                state.EntityManager.SetComponentData(entities[i], localTransform);
            }

        }
    }
}